﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Linq;
using System.IO;
using System.Text.Json;

namespace ClickScreen
{
    public partial class MainForm : Form
    {
        private class ClickPoint
        {
            public Point Location { get; set; }
            public float Interval { get; set; }
        }

        [DllImport("user32.dll")]
        static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);

        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        private const uint MOUSEEVENTF_LEFTDOWN = 0x0002;
        private const uint MOUSEEVENTF_LEFTUP = 0x0004;
        private const uint MOD_CONTROL = 0x0002;
        private const int HOTKEY_ID = 1;

        private List<ClickPoint> points = new List<ClickPoint>();
        private bool isRecording = false;
        private bool isClicking = false;
        private System.Windows.Forms.Timer recordTimer;

        private class ClickPlan
        {
            public string Name { get; set; }
            public List<ClickPoint> Points { get; set; } = new List<ClickPoint>();
        }

        private List<ClickPlan> plans = new List<ClickPlan>();
        private ClickPlan currentPlan;
        private const int MAX_PLANS = 3;

        private const string PLANS_FILE = "clickplans.json";
        private string PlansFilePath => Path.Combine(Application.StartupPath, PLANS_FILE);
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x0312 && m.WParam.ToInt32() == HOTKEY_ID)
            {
                isClicking = false;
                this.WindowState = FormWindowState.Normal;
            }
            base.WndProc(ref m);
        }
        public MainForm()
        {
            InitializeComponent();
            LoadPlans();  // 加载保存的方案
            if (plans.Count == 0)  // 如果没有保存的方案，创建默认方案
            {
                for (int i = 0; i < MAX_PLANS; i++)
                {
                    plans.Add(new ClickPlan { Name = $"方案 {i + 1}" });
                }
            }
            currentPlan = plans[0];
            SetupUI();
            RegisterHotKey(this.Handle, HOTKEY_ID, MOD_CONTROL, (uint)Keys.Q);
        }

        private void LoadPlans()
        {
            try
            {
                if (File.Exists(PlansFilePath))
                {
                    string json = File.ReadAllText(PlansFilePath);
                    plans = JsonSerializer.Deserialize<List<ClickPlan>>(json);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载方案失败: {ex.Message}", "错误");
                plans = new List<ClickPlan>();
            }
        }

        private void SavePlans()
        {
            try
            {
                string json = JsonSerializer.Serialize(plans);
                File.WriteAllText(PlansFilePath, json);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存方案失败: {ex.Message}", "错误");
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            SavePlans();  // 关闭程序时保存方案
            UnregisterHotKey(this.Handle, HOTKEY_ID);
            base.OnFormClosing(e);
        }

        // 修改记录按钮和清除按钮的事件处理，在数据变化后保存方案
        private void SetupUI()
        {
            this.Text = "屏幕点击器";
            this.Size = new Size(600, 400);

            // 控制面板
            var controlPanel = new Panel
            {
                Dock = DockStyle.Top,
                Height = 80
            };

            var intervalLabel = new Label
            {
                Text = "点击间隔(秒):",
                Location = new Point(10, 20),
                BackColor = Color.Transparent,
                AutoSize = true
            };

            var intervalInput = new TextBox
            {
                Text = "1.0",
                Location = new Point(95, 18),
                Width = 60,
                TextAlign = HorizontalAlignment.Right
            };
            intervalLabel.SendToBack();
            var repeatLabel = new Label
            {
                Text = "重复次数:",
                Location = new Point(160, 20),
                BackColor = Color.Transparent,
                AutoSize = true
            };
            repeatLabel.SendToBack();
            var repeatInput = new TextBox
            {
                Text = "1",
                Location = new Point(220, 18),
                Width = 60,
                TextAlign = HorizontalAlignment.Right
            };

            var recordButton = new Button
            {
                Text = "开始记录",
                Location = new Point(290, 15)
            };

            var startButton = new Button
            {
                Text = "开始点击",
                Location = new Point(390, 15)
            };

            // 点位列表
            // 修改列表视图列
            var listView = new ListView
            {
                Dock = DockStyle.Fill,
                View = View.Details,
                LabelEdit = true,
                FullRowSelect = true
            };
            listView.Columns.Add("X坐标", 100);
            listView.Columns.Add("Y坐标", 100);
            listView.Columns.Add("间隔(秒)", 100);

            listView.MouseDoubleClick += (s, e) =>
            {
                if (listView.SelectedItems.Count > 0)
                {
                    int columnIndex = -1;
                    if (e.X <= listView.Columns[0].Width)
                        columnIndex = 0;
                    else if (e.X <= listView.Columns[0].Width + listView.Columns[1].Width)
                        columnIndex = 1;
                    else if (e.X <= listView.Columns[0].Width + listView.Columns[1].Width + listView.Columns[2].Width)
                        columnIndex = 2;

                    if (columnIndex >= 0)
                    {
                        var subItem = listView.SelectedItems[0].SubItems[columnIndex];
                        var bounds = subItem.Bounds;
                        var editor = new TextBox
                        {
                            Text = subItem.Text,
                            Bounds = bounds,
                            BorderStyle = BorderStyle.FixedSingle
                        };

                        editor.LostFocus += (sender, args) =>
                        {
                            bool isValid = false;
                            if (columnIndex == 2) // 间隔时间
                            {
                                if (float.TryParse(editor.Text, out float newInterval))
                                {
                                    currentPlan.Points[listView.SelectedItems[0].Index].Interval = newInterval;
                                    subItem.Text = newInterval.ToString();
                                    isValid = true;
                                }
                            }
                            else // X或Y坐标
                            {
                                if (int.TryParse(editor.Text, out int newValue))
                                {
                                    var point = currentPlan.Points[listView.SelectedItems[0].Index].Location;
                                    if (columnIndex == 0)
                                        point.X = newValue;
                                    else
                                        point.Y = newValue;
                                    currentPlan.Points[listView.SelectedItems[0].Index].Location = point;
                                    subItem.Text = newValue.ToString();
                                    isValid = true;
                                }
                            }
                            if (isValid)
                                SavePlans();
                            listView.Controls.Remove(editor);
                        };

                        editor.KeyPress += (sender, args) =>
                        {
                            if (args.KeyChar == (char)Keys.Enter)
                            {
                                editor.Parent.Focus();
                                args.Handled = true;
                            }
                            else if (args.KeyChar == (char)Keys.Escape)
                            {
                                listView.Controls.Remove(editor);
                                args.Handled = true;
                            }
                        };

                        listView.Controls.Add(editor);
                        editor.Focus();
                    }
                }
            };

         

            var deleteButton = new Button
            {
                Text = "删除选中",
                Dock = DockStyle.Bottom
            };

            var clearButton = new Button
            {
                Text = "删除全部",
                Dock = DockStyle.Bottom
            };

            // 在控制面板添加方案选择
            var planLabel = new Label
            {
                Text = "当前方案:",
                Location = new Point(10, 50),
                AutoSize = true
            };

            var planComboBox = new ComboBox
            {
                Location = new Point(95, 48),
                Width = 80,
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            planComboBox.Items.AddRange(plans.Select(p => p.Name).ToArray());
            planComboBox.SelectedIndex = -1;

            planComboBox.SelectedIndexChanged += (s, e) =>
            {
                currentPlan = plans[planComboBox.SelectedIndex];
                listView.Items.Clear();
                foreach (var point in currentPlan.Points)
                {
                    listView.Items.Add(new ListViewItem(new[] {
                        point.Location.X.ToString(),
                        point.Location.Y.ToString(),
                        point.Interval.ToString()
                    }));
                }
            };
            planComboBox.SelectedIndex = 0;
            // 修改记录逻辑中的points引用
            recordButton.Click += (s, e) =>
            {
                if (!isRecording)
                {
                    isRecording = true;
                    recordButton.Text = "停止记录";
                    this.WindowState = FormWindowState.Minimized;
                    recordTimer = new System.Windows.Forms.Timer();
                    recordTimer.Interval = 100;
                    recordTimer.Tick += (sender, args) =>
                    {
                        if (Control.MouseButtons == MouseButtons.Left)
                        {
                            var point = Cursor.Position;
                            var clickPoint = new ClickPoint 
                            { 
                                Location = point,
                                Interval = float.Parse(intervalInput.Text)
                            };
                            currentPlan.Points.Add(clickPoint);
                            listView.Items.Add(new ListViewItem(new[] { 
                                point.X.ToString(), 
                                point.Y.ToString(),
                                clickPoint.Interval.ToString()
                            }));
                        }
                    };
                    recordTimer.Start();
                }
                else
                {
                    isRecording = false;
                    recordButton.Text = "开始记录";
                    this.WindowState = FormWindowState.Normal;
                    recordTimer.Stop();
                    SavePlans();  // 记录完成后保存
                }
            };

            clearButton.Click += (s, e) =>
            {
                if (currentPlan.Points.Count > 0)
                {
                    if (MessageBox.Show("确定要删除所有点位吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        currentPlan.Points.Clear();
                        listView.Items.Clear();
                        SavePlans();  // 清除后保存
                    }
                }
            };

            deleteButton.Click += (s, e) =>
            {
                if (listView.SelectedItems.Count > 0)
                {
                    var index = listView.SelectedItems[0].Index;
                    currentPlan.Points.RemoveAt(index);
                    listView.Items.RemoveAt(index);
                    SavePlans();  // 删除后保存
                }
            };

            startButton.Click += async (s, e) =>
            {
                if (currentPlan.Points.Count == 0)
                {
                    MessageBox.Show("请先记录点击位置！", "警告");
                    return;
                }

                if (!float.TryParse(intervalInput.Text, out float interval) ||
                    !int.TryParse(repeatInput.Text, out int repeat))
                {
                    MessageBox.Show("请输入有效的间隔时间和重复次数！", "错误");
                    return;
                }

                this.WindowState = FormWindowState.Minimized;
                Thread.Sleep(1000);
                isClicking = true;

                await Task.Run(() =>
                {
                    for (int i = 0; i < repeat && isClicking; i++)
                    {
                        foreach (var point in currentPlan.Points)
                        {
                            if (!isClicking) break;
                            Cursor.Position = point.Location;
                            mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP,
                                (uint)point.Location.X, (uint)point.Location.Y, 0, 0);
                            Thread.Sleep((int)(point.Interval * 1000));
                        }
                    }

                    this.Invoke((MethodInvoker)delegate
                    {
                        isClicking = false;
                        this.WindowState = FormWindowState.Normal;
                        MessageBox.Show("点击任务已完成！", "完成");
                    });
                });
            };
            // 添加新控件到控制面板
            controlPanel.Controls.AddRange(new Control[] {
                intervalLabel, intervalInput,
                repeatLabel, repeatInput,
                recordButton, startButton,
                planLabel, planComboBox
            });

            // 修改添加控件部分
            // 在删除按钮之前添加新增按钮
            var addButton = new Button
            {
                Text = "添加记录",
                Dock = DockStyle.Bottom
            };

            addButton.Click += (s, e) =>
            {
                var newPoint = new ClickPoint
                {
                    Location = new Point(0, 0),
                    Interval = float.Parse(intervalInput.Text)
                };
                currentPlan.Points.Add(newPoint);
                listView.Items.Add(new ListViewItem(new[] {
                    "0",
                    "0",
                    intervalInput.Text
                }));
                SavePlans();
            };

            // 修改控件添加顺序
            this.Controls.Add(clearButton);
            this.Controls.Add(deleteButton);
            this.Controls.Add(addButton);  // 添加新按钮
            this.Controls.Add(listView);
            this.Controls.Add(controlPanel);
        }
    }
}

